<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import request from "@/utils/request.js"
import { User, Lock } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()
const role = ref('USER') // 默认选择普通用户

// 角色选项与用户管理模块保持一致
const roleOptions = {
  USER: "用户",
  RIDER: "骑手",
  ADMIN: "管理员"
};

const handleRegister = () => {
  router.push('/register')
}

const formData = ref({
  account: '',
  password: '',
  role: 'USER'
})

// 验证规则
const rules = ref({
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
})

// 获取表单引用
const formRef = ref(null)

const handleLogin = async () => {
  try {
    await formRef.value.validate()
    
    const response = await request.post('/login', {
      username: formData.value.account,
      password: formData.value.password,
      role: role.value
    })

    if (response.code === 200) {
      // 获取返回数据
      const responseData = response.data;
      // 提取用户信息和token
      const userInfo = responseData.userInfo;
      const token = responseData.token || '';
      
      console.log('登录成功:', responseData);
      console.log('用户信息:', userInfo);
      console.log('Token:', token);
      
      // 1. 保存到localStorage
      localStorage.setItem('user', JSON.stringify(userInfo));
      localStorage.setItem('token', token);
      
      // 2. 保存到Pinia状态管理
      userStore.setUser(userInfo);
      userStore.setToken(token);
      
      ElMessage.success('登录成功');
      
      // 根据角色跳转
      if(userInfo.role === 'ADMIN'){
        router.push('/admin');
      } else if (userInfo.role === 'RIDER'){
        router.push('/rider');
      } else {
        router.back();
      }
    } else {
      ElMessage.error(response.message || '登录失败')
    }
  } catch (error) {
    ElMessage.error('登录失败')
    console.error('登录请求失败:', error)
  }
}
</script>

<template>
  <div class="container">
    <el-card class="login-card">
      <div slot="header" class="card-header">
        <!-- 新增返回主页链接 -->
        <el-link 
          :underline="false" 
          @click="router.push('/')" 
          class="home-link"
        >
          &lt; 返回主页
        </el-link>
        <span class="welcome-text">登录</span>
      </div>
      <el-form 
        ref="formRef" 
        :model="formData" 
        :rules="rules"
        @submit.prevent>
        
        <el-form-item prop="account">
          <el-input 
            :prefix-icon="User" 
            v-model="formData.account" 
            placeholder="请输入账号" />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input 
            :prefix-icon="Lock" 
            v-model="formData.password" 
            type="password" 
            placeholder="请输入密码" 
            show-password />
        </el-form-item>

        <el-form-item 
          label="身份"
          class="role-form-item">
          <el-select 
            v-model="role" 
            placeholder="请选择角色" 
            class="role-select">
            <el-option
              v-for="(label, value) in roleOptions"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>

        <div class="button-group">
          <el-button type="primary" @click="handleLogin" class="login-btn">立即登录</el-button>
          <el-link
            :underline="false"
            @click="handleRegister"
          >
            还没有账号？立即注册
          </el-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped>
/* 调整角色选择器样式 */
:deep(.el-select.role-select) {
    --el-font-size-base: 16px;
    width: 100%;
}

:deep(.el-select.role-select .el-input__inner) {
    height: 40px;
    line-height: 40px;
    font-size: var(--el-font-size-base);
}

:deep(.el-select.role-select .el-select__caret) {
    font-size: var(--el-font-size-base);
}

:deep(.el-select-dropdown__item) {
    font-size: var(--el-font-size-base);
    padding: 8px 32px;
}

.container {
    background-image: url("@/assets/bg.png");
    width: 100%;
    height: 100vh;
    background-size: cover;
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
}

.login-card {
    padding-top: 20px;
    width: 450px;
}

/* 新增链接样式 */
.card-header {
  position: relative;
  text-align: center;
  margin-bottom: 25px;
}

.home-link {
  position: absolute;
  left: 5px;
  top: 0;
  transform: translateY(-50%);
  font-size: 14px;
  color: var(--el-color-primary);
}

.welcome-text {
  font-size: 24px;
  font-weight: 600;
}

:deep(.el-form-item__label) {
  font-size: 16px;
}
:deep(.el-input__inner) {
  font-size: 16px;
  height: 40px;
}

.button-group {
  margin-top: 25px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

:deep(.login-btn) {
  width: 100%;
  height: 45px;
  font-size: 16px;
}

/* 调整输入框容器宽度 */
:deep(.role-form-item .el-form-item__content) {
  flex: 1;
  min-width: 0; /* 防止内容溢出 */
}
</style>